<script setup>

import {onMounted, ref, watch, defineExpose, onUnmounted, nextTick} from "vue";
import {message} from "ant-design-vue";
import jumpHelper from "@/js/pageJumper";
import {getAllMessages, getUserId, messageImgUrl, websocketUrl} from "@/js/apiHelper";
import {timeCorrect} from "@/js/jsHelper";

onMounted(()=>{
  //获取token
  token.value = localStorage.getItem('token')
  //获取当前用户id
  getUserIdByToken(token.value)
  //设置图片上传网址
  uploadHeaders.value = {
    Authorization: 'Bearer '+token.value
  }
})
const scrollContainer = ref()
//选择对话后
const changeDialogue = (e)=>{
  uploadUrl.value = messageImgUrl + '?messageId='+e.messageId;
  console.log(uploadUrl.value)
  otherId.value = e.otherUserId
  dialogueId.value = e.messageId
  startWebSocket(userId.value)
  getAllMessagesByDialogueId(e.dialogueId)
}
defineExpose({changeDialogue})
//token
const token = ref('')
//userId
const userId = ref('')
const otherId = ref('')
//messageId
const dialogueId = ref('')
const getUserIdByToken = (token)=>{
  const postResult = getUserId(token);
  postResult.then(response=>{
    userId.value = response.data.data
  }).catch(e=>{
    console.log(e)
    message.error('解析token失败，可能登陆过期，请重新登录')
    jumpHelper.jumpToSign()
  })
}
//输入文字
const inputText = ref('')
//上传图片
const fileList = ref([]);
const uploadHeaders = ref('');
const uploadUrl = ref('');
const fileUrl = ref('')
watch(
    ()=>fileList.value,
    (newValue)=>{
      if (newValue[0]?.status === 'done'){
        fileUrl.value = newValue[0].response.data;
      }
    }
)
//获取所有消息
const allMessages = ref([])
const getAllMessagesByDialogueId = (dialoguaId)=>{
  const postResult = getAllMessages(token.value, dialoguaId);
  postResult.then(response=>{
    if (response.data.success === 1){
      const messageList = response.data.data;
      for (const messageListElement of messageList) {
        messageListElement.sendTime = timeCorrect(messageListElement.sendTime)
      }
      allMessages.value = messageList;
      nextTick(() => {
        // 滚动到底部
        scrollContainer.value.scrollTo({
          top: scrollContainer.value.scrollHeight,
          behavior: 'smooth',
        });
      });
    }else {
      message.error('获取消息时出错')
    }
  }).catch(e=>{
    message.error('获取消息时出错，'+e)
  })
}
//建立websocket
const ws = ref('')
const startWebSocket=()=>{
  try {
    ws.value = new WebSocket(websocketUrl+userId.value);
    ws.value.onmessage = getMessage
    ws.value.onerror = onError
  }catch (e){
    message.error('与服务器建立websocket对话失败，'+e)
  }
}
const onError = ()=>{
  message.error('websocket连接出错，请重新选择对话')
}
//收到消息
const getMessage = (msg)=>{
  var messageDetail = JSON.parse(msg.data)
  messageDetail.sendTime = timeCorrect(messageDetail.sendTime)
  allMessages.value.push(messageDetail)

  nextTick(()=>{
    scrollContainer.value.scrollTo({
      top: scrollContainer.value.scrollHeight,
      behavior: 'smooth',
    });
  })
}
//发送消息
const sendMessage = ()=>{
  if (ws.value && ws.value.readyState === WebSocket.OPEN){
    try {
      ws.value.send(JSON.stringify({
        messageId: dialogueId.value,
        toUserId: otherId.value,
        messageContent: inputText.value,
        messageImg: fileUrl.value
      }))
      inputText.value = ''
      fileList.value = []
      fileUrl.value = ''
    }catch (e){
      message.error('发送失败，'+e)
    }
  }else{
    message.error('发送失败，请先选择会话')
  }
}

onUnmounted(()=>{
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.close();
  }
})


</script>

<template>
  <div class="message-com-all-container">
    <img class="logo-self" src="@/assets/logo.png">
    <!--消息-->
    <div ref="scrollContainer" class="message-container">
      <div class="one-msg-container" :class="message.senderId === userId ? 'myMsg' : 'otherMsg'" v-for="(message, index) in allMessages" :key="index">
        <div class="msg-head">
          <div>{{message.nickName}}</div>
          <div>{{message.sendTime}}</div>
        </div>
        <div class="msg-container">
          <div>{{message.messageContent}}</div>
          <img v-if="message.messageImg && message.messageImg.length > 5" :src="message.messageImg">
        </div>
      </div>
    </div>
    <!--发送-->
    <div class="send-container">
      <!--输入-->
      <div class="text-container">
        <a-textarea
            class="text-area-self"
            v-model:value="inputText"
            placeholder="请输入聊天内容"
            :auto-size="{ minRows: 1, maxRows: 5 }"
        />
        <a-button v-if="uploadUrl.length>1" @click="sendMessage" size="small" type="primary" class="send-btn">发送</a-button>
        <a-button v-else size="small" type="default" disabled class="send-btn"></a-button>
      </div>
      <!--图片-->
      <div class="photo-container">
        <a-upload
            v-model:file-list="fileList"
            name="file"
            :max-count="1"
            :action="uploadUrl"
            :headers="uploadHeaders"
        >
          <a-button v-if="uploadUrl.length>1" size="small" type="primary" class="my-btn">
            上传图片
          </a-button>
          <a-button v-else size="small" type="default" disabled class="my-btn">未选对话</a-button>
        </a-upload>
      </div>
    </div>
  </div>
</template>

<style scoped>
  .message-com-all-container{
    height: calc(100% - 12px);
    width: calc(100% - 360px);
    background-color: #fbfbfb88;
    border-radius: 8px;
    box-shadow: 2px 2px 8px rgba(0,0,0,0.1);
    user-select: none;
    padding: 16px 12px;
    display: flex;
    flex-direction: column;
  }
  .logo-self{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    max-width: 240px;
    opacity: .4;
  }
  /*消息列表*/
  .message-container{
    flex: 1;
    position: relative;
    overflow-y: scroll;
    transition: scroll-behavior 0.5s ease-in-out; /* 添加过渡效果 */
  }
  .one-msg-container{
    min-height: 36px;
    width: 100%;
    margin-bottom: 12px;
    display: flex;
    flex-direction: column;
  }
  .msg-head{
    width: 100%;
    height: 24px;
    display: flex;
    align-items: center;
  }
  .msg-head div:nth-child(1){
    font-size: 18px;
    letter-spacing: 2px;
    color: #333;
  }
  .msg-head div:nth-child(2){
    margin: 0 8px;
    color: #555;
    font-size: 12px;
  }
  .myMsg .msg-head{
    justify-content: right;
    flex-direction: row-reverse;
  }
  .msg-container{
    margin-top: 4px;
    max-width: 80%;
    border-bottom-right-radius: 8px;
    border-bottom-left-radius: 8px;
    display: flex;
    flex-direction: column;
    padding: 8px 12px;
  }
  .msg-container img{
    width: 100%;
    margin: 8px 0;
    border-radius: 4px;
    align-self: center;
  }
  .myMsg .msg-container{
    align-self: end;
    background-color: #458df6;
    border-top-left-radius: 8px;
    color: white;
  }
  .otherMsg .msg-container{
    align-self: start;
    background-color: #fff;
    border-top-right-radius: 8px;
    color: #333;
  }


  /*输入框*/
  .send-container{
    margin-top: 8px;
    min-height: 64px;
    position: relative;
    display: flex;
    align-items: end;
    justify-content: space-between;
  }
  .text-container{
    width: calc(100% - 176px);
    min-height: 52px;
    display: flex;
    align-items: center;
    padding: 0 76px 0 8px;
    border: 2px solid #b6c4d5;
    border-radius: 8px;
    position: relative;
    background-color: #ffffff88;
  }
  .photo-container{
    width: 168px;
    height: 52px;
    position: relative;
    border: 2px solid #b6c4d5;
    border-radius: 8px;
    background-color: #ffffff88;
  }
  .text-area-self{
    background-color: transparent;
    border: none;
    outline: none;
    box-shadow: none;
  }
  .send-btn{
    position: absolute;
    right: 12px;
    height: 32px;
    width: 56px;
    bottom: 9px;
  }
  .my-btn{
    position: absolute;
    height: 32px;
    width: 80px;
    left: 8px;
    bottom: 9px;
  }
  ::v-deep .ant-upload-list{
    position: absolute;
    width: 56px;
    right: 4px;
    bottom: 14px;
  }
</style>